package com.cy.ppj.comm.interceptor;

import com.cy.ppj.comm.constant.Constants;
import com.cy.ppj.comm.exception.MsgException;
import com.cy.ppj.comm.utils.CommonUtils;
import com.cy.ppj.service.wechat.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 用户登录拦截器
 * @author: Ocean
 * @create: 2018-07-23 17:03
 **/
@Slf4j
@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WechatService wechatService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //从头部获取token
        String token = httpServletRequest.getHeader(Constants.TOKEN);
        if (StringUtils.isEmpty(token) && CommonUtils.isWechatClient(httpServletRequest)) {
            String url = wechatService.getAutoLoginUrl();
            //没有Token且微信客户端请求
            throw new MsgException("未登录", -2000, url);
        } else if (StringUtils.isEmpty(token)) {
            throw new MsgException("未登录", -1000);
        }
        String key = Constants.USER_LOGIN_KEY.concat(token);
        boolean hasKey = redisTemplate.hasKey(key);
        //查询是否存在
        if (!hasKey && CommonUtils.isWechatClient(httpServletRequest)) {
            String url = wechatService.getAutoLoginUrl();
            //没有Token且微信客户端请求
            throw new MsgException("登录已失效", -2000, url);
        } else if (!hasKey) {
            throw new MsgException("登录已失效", -1000);
        }
        //重新设置过期时间
        redisTemplate.expire(key, Constants.LOGIN_TIME, Constants.LOGIN_TIME_UNIT);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
